﻿using System.Text.Json;
using MeiWinForms.comm;
using MeiWinForms.communication;
using static MeiWinForms.tool.MeiFile;
using static MeiWinForms.comm.Utils;
using static MeiWinForms.comm.Config;


namespace MeiWinForms.module;

public static class SqlBackup
{
    public static async void Backup()
    {
        try
        {
            Output.WriteOutput("开始同步数据库备份");
            using var client = new AsyncClient("backup_sql");
            string host = GetLocalIp();
            var fileListJsonElement = (JsonElement)await client.Send(host + ":99");
            JsonElement.ArrayEnumerator fileListEnumerateArray = fileListJsonElement.GetProperty("file_list").EnumerateArray();
            var fileList = fileListEnumerateArray.Select(fileNameElement =>
                fileNameElement.GetString()).OfType<string>();
            foreach (string fileName in fileList)
            {
                string filePath = DataPath("sql_backup", fileName);
                if (File.Exists(filePath))
                {
                    continue;
                }

                await client.Send(fileName);
                int ret = recvFile(filePath, host, 99); // TODO 不知道为什么输出没有打出来
                Output.WriteOutput($"接收文件 {fileName} 结果：{ret.ToString()}");
            }

            await client.Send("");
            Output.WriteOutput("同步完成！");
        }
        catch (Exception e)
        {
            Output.WriteOutput(e.ToString());
        }
    }
}